//
//  DZQualityViewController.m
//  DaoZiJinFu
//
//  Created by dzjf on 2017/1/13.
//  Copyright © 2017年 dzjf. All rights reserved.
//

#import "DZQualityViewController.h"
#import "DZQualityHeadCell.h"
#import "DZQualityContentCell.h"
#import "DZQulityEnterCell.h"
#import "BottomToolBar.h"
#import "VoucherModel.h"
#import "SubmitPurchase.h"
#import "ProtocolVC.h"
#import "MoreIntroduceTableViewController.h"
#import "SafetyViewController.h"
#import "LZSecutyViewController.h"
@interface DZQualityViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    CalculateView *calculate;
}
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) DZQualityModel *qualityModel;
@end

@implementation DZQualityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self leftButton:nil];
    [self setTableView];
    [self getInfo];
}

- (void)getInfo {
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"Index/getProductDetail";
    request.params = @{@"id":@(_productId)?:@""};
    [DZNetAPI request:request success:^(id response) {
        NSLog(@"%@",response);
        DZResponse *res = [DZResponse mj_objectWithKeyValues:response];
        if (res.rt == 1) {
            _qualityModel = [DZQualityModel mj_objectWithKeyValues:res.data];
            [self.tableView reloadData];
            [self selectFoot];
        }else{
            JSSHOW(res.msg);
        }
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)selectFoot {
    [self setToolBar];
}

- (void)setToolBar {
    BottomToolBar *toolBar = [[BottomToolBar alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-TOOLBAR_HEIGHT, SCREEN_WIDTH, TOOLBAR_HEIGHT)];
    [toolBar.investBtn addTarget:self action:@selector(investBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [toolBar.calculate addTarget:self action:@selector(calculateClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:toolBar];
}

- (void)setFootView:(NSString *)string {
     UILabel *toolBar = [[UILabel alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-TOOLBAR_HEIGHT, SCREEN_WIDTH, TOOLBAR_HEIGHT)];
    toolBar.backgroundColor = GRAYCOLOR;
    toolBar.textColor = [UIColor whiteColor];
    toolBar.font = [UIFont boldSystemFontOfSize:18];
    toolBar.text = string;
    toolBar.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:toolBar];
    toolBar.userInteractionEnabled = YES;
    [toolBar addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backPage)]];
}
- (void)backPage {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)investBtnClick {
    if (userValue(ISLOGIN) == nil || [userValue(ISLOGIN) boolValue] == NO) {
        if (userValue(HOSTTEL)) {
            LoginViewController *login = [[LoginViewController alloc] init];
            login.telNum = userValue(HOSTTEL);
            [self.navigationController pushViewController:login animated:YES];
        } else {
            RegisterViewController *join = [[RegisterViewController alloc] init];
            [self.navigationController pushViewController:join animated:YES];
        }
    } else {
        if ([userValue(ISBINDCARD) boolValue] == NO) {
            BindCardTableVC *bindCard = [[BindCardTableVC alloc] init];
            [self.navigationController pushViewController:bindCard animated:YES];
        } else {
            [self getCouponList];
        }
    }
}

- (void)getCouponList {
    JSSHOWHUD;
    NSDictionary *params = @{@"day":[NSString stringWithFormat:@"%ld",_qualityModel.day_number],@"status":@1,@"pagesize":@100};
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.requestUrl = @"User/getCouponList";
    request.httpMethod = @"GET";
    request.params = params;
    [DZNetAPI request:request success:^(id responseObject) {
        JSHIDEHUD;
        NSLog(@"%@",responseObject);
        DZResponse *model = [DZResponse mj_objectWithKeyValues:responseObject];
        if (model.rt == 1) {
            NSArray *arr =model.data[@"list"];
            NSMutableArray *listArray = [NSMutableArray array];
            listArray = [VoucherModel mj_objectArrayWithKeyValuesArray:arr];
            for (VoucherModel *model in listArray) {
                model.flag = [model.amount integerValue];
            }
            NSSortDescriptor *amountDesc = [NSSortDescriptor sortDescriptorWithKey:@"_flag" ascending:NO];
            NSSortDescriptor *limitAmount = [NSSortDescriptor sortDescriptorWithKey:@"_limit_amount" ascending:YES];
            NSArray *descs = @[amountDesc,limitAmount];
            [listArray sortedArrayUsingDescriptors:descs];
            NSMutableArray *temoArray = [NSMutableArray arrayWithArray:listArray];
            [listArray removeAllObjects];
            for (NSInteger i = temoArray.count - 1; i >=0 ; i --) {
                [listArray addObject:temoArray[i]];
            }
            [self enterSubpage:listArray];
        }
    } failure:^(NSError *error) {
        JSSHOW(LOAD_FAIL_TIP);
    }];
}

- (void)enterSubpage:(NSArray *)listArray {
    SubmitPurchase *submitPurchase = [[SubmitPurchase alloc] init];
    UILabel *titleLab = (UILabel *)self.navigationItem.titleView;
    [submitPurchase setupTitleView:titleLab.text];
    if (listArray.count) {
        submitPurchase.voucherArray = listArray;
    }
    HomeCellModel *model = [[HomeCellModel alloc] init];
    model.name = _qualityModel.name;
    model.remaining_investment_amount = _qualityModel.remaining_investment_amount;
    model.buy_max_amount = _qualityModel.buy_max_amount;
    model.buy_min_amount = _qualityModel.buy_min_amount;
    model.day_number = _qualityModel.day_number;
    model.annual_gains = _qualityModel.annual_gains;
    model.remaining_investment_amount = _qualityModel.remaining_investment_amount;
    model.id = [NSString stringWithFormat:@"%ld",_qualityModel.id];
    submitPurchase.model = model;
    submitPurchase.annual_gains = _qualityModel.annual_gains;
    submitPurchase.remaining_investment_amount = _qualityModel.remaining_investment_amount;
    [self.navigationController pushViewController:submitPurchase animated:YES];
}

- (void)calculateClick {
    CGFloat data_number = _qualityModel.day_number;
    CGFloat annual_gains = _qualityModel.annual_gains;
    calculate = [CalculateView showView:self.view];
    calculate.dateText.text = [NSString stringWithFormat:@"%.0lf",data_number];
    calculate.moneyText.text = @"10000";
    float money = [DZNsstringUtil floatInto:10000*annual_gains*(data_number/365.0)];
    calculate.income.text = [NSString stringWithFormat:@"%.2lf",money];
    [calculate.moneyText addTarget:self action:@selector(moneyTextEdit) forControlEvents:UIControlEventEditingChanged];
    [calculate.dateText addTarget:self action:@selector(moneyTextEdit) forControlEvents:UIControlEventEditingChanged];
}

- (void)moneyTextEdit {
    CGFloat annual_gains = _qualityModel.annual_gains;
    if (calculate.moneyText.text.length == 0 || calculate.dateText.text.length == 0) {
        calculate.income.text = @"0.00";
    } else {
        float money = [DZNsstringUtil floatInto:[calculate.moneyText.text doubleValue]*annual_gains*([calculate.dateText.text doubleValue]/365.0)];
        calculate.income.text = [NSString stringWithFormat:@"%.2lf",money];
    }
}


- (void)setTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TOOLBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:DZQualityHeadCells bundle:nil] forCellReuseIdentifier:DZQualityHeadCells];
    [self.tableView registerNib:[UINib nibWithNibName:DZQualityContentCells bundle:nil] forCellReuseIdentifier:DZQualityContentCells];
    [self.tableView registerNib:[UINib nibWithNibName:DZQulityEnterCells bundle:nil] forCellReuseIdentifier:DZQulityEnterCells];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [JSViewUtil setSecutyView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        return 3;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01;
    }
    return 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        return 111;
    }else if (indexPath.section == 2){
        return 48;
    }
    return  205;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.section == 0) {
         DZQualityHeadCell *cells = [self.tableView dequeueReusableCellWithIdentifier:DZQualityHeadCells];
        cells.model = _qualityModel?:nil;
        cell = cells;
    }else if (indexPath.section == 1) {
        DZQualityContentCell *cells = [self.tableView dequeueReusableCellWithIdentifier:DZQualityContentCells];
        cell = cells;
    }else if(indexPath.section == 2) {
        DZQulityEnterCell *cells = [self.tableView dequeueReusableCellWithIdentifier:DZQulityEnterCells];
        cells.isSelling = NO;
        switch (indexPath.row) {
            case 0:
                cells.content.text = @"查看更多介绍";
                break;
            case 1:
                cells.content.text = @"安全保障";
                break;
            case 2:
                cells.content.text = @"投资服务协议";
                break;
            default:
                break;
        }
        cell = cells;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        switch (indexPath.row) {
            case 0:
                [self skipToMoreIntroduce];
                break;
            case 1:
                [self skipToSecurity];
                break;
            case 2:
                [self skipToProtocol];
                break;
            default:
                break;
        }
    }
}
- (void)skipToMoreIntroduce {
    MoreIntroduceTableViewController *moreIntroduce = [[MoreIntroduceTableViewController alloc] init];
    [self.navigationController pushViewController:moreIntroduce animated:YES];
}
- (void)skipToSecurity {
    LZSecutyViewController *safety = [[LZSecutyViewController alloc] init];
    safety.flag = 1;
    [self.navigationController pushViewController:safety animated:YES];
}
- (void)skipToProtocol {
    ProtocolVC *protocol = [[ProtocolVC alloc] init];
    protocol.protocolType = 2;
    [self.navigationController pushViewController:protocol animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

@implementation DZQualityModel

@end
